package com.google.code.DB2SMS;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.code.gezerlis.R;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.telephony.SmsManager;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class DB2SMSClientActivity extends Activity implements Runnable {
	TextView t;
	Thread runner;
	int i = 0; 
	int period = 5;
	final Handler mHandler = new Handler();
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

	final Runnable updater = new Runnable() {
		public void run() {
			scanEmailAndSendSms();
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		t = (TextView) findViewById(R.id.editText1);
		
        Button btn1 = (Button) findViewById(R.id.button1);  
	    btn1.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();             
		    	System.exit(0); 
			}
		}); 
	    scanEmailAndSendSms();
	    if (runner == null){
			runner = new Thread(this);            
			runner.start();         
			} 
	}

	public void run() {
		while (runner != null) {
			try {
				Thread.sleep(period*1000);
			} catch (InterruptedException e) {
			}
			;
			mHandler.post(updater);
		}
	}

	public void scanEmailAndSendSms() {
		t = (TextView) findViewById(R.id.editText1);
		String filestr = "/db2sms/sms.txt";
		t.setText(dateFormat.format(new Date())+"\n\n"+"SCANNING /sdcard"+filestr+" FOR PENDING SMS\n");
		try {
			File sdcard = Environment.getExternalStorageDirectory(); 
			File file = new File(sdcard, filestr);
			StringBuilder text = new StringBuilder(); 
			BufferedReader br = new BufferedReader(new FileReader(file)); 
			String line;      
			while ((line = br.readLine()) != null) {         
				         
				String phone = line.substring(0, line.indexOf("#"));
				String message = line.substring(line.indexOf("#")+1);
				t.append(phone);
				t.append("\n"); 
				t.append(message);
				t.append("\n"); 
				SmsManager sms = SmsManager.getDefault();
		        sms.sendTextMessage(phone, null, message, null, null);        
		        appendLog(dateFormat.format(new Date())+"\t"+phone+"\t"+message);
				} 
			boolean deleted = file.delete(); 
			t.append("Deleted /sdcard"+filestr+": "+String.valueOf(deleted)+"\n");
			
			
		} catch (Exception e) {
			Log.v("Exception", e.getMessage());
			//appendLog( e.getMessage());
		}
		t.append("SCAN FINISHED FOR PENDING SMS's.\n\nNext scan in "+String.valueOf(period)+"\"\n");
	}
	
	public void appendLog(String text)
	{       
	   File logFile = new File("/sdcard/db2sms/db2smsclient.log");
	   if (!logFile.exists())
	   {
	      try
	      {
	         logFile.createNewFile();
	      } 
	      catch (IOException e)
	      {
	         // TODO Auto-generated catch block
	    	  Log.v("Exception", e.getMessage());
	      }
	   }
	   try
	   {
	      //BufferedWriter for performance, true to set append to file flag
	      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
	      buf.append(text);
	      buf.newLine();
	      buf.close();
	   }
	   catch (IOException e)
	   {
	      // TODO Auto-generated catch block
		   Log.v("Exception", e.getMessage());
	   }
	}

}